<template>
    <div class="app-container">

        <el-form :model="params" ref="queryForm" size="mini" :inline="true" label-width="120px">
            <el-form-item label="学院" prop="deptId">
                <el-select @change="changeDept" v-model="params.deptId" placeholder="请选择学院" filterable clearable>
                    <el-option v-for="(v, i) in deptList" :key="i" :label="v.label" :value="v.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="专业" prop="majorId">
                <el-select @change="changeMajor" v-model="params.majorId" placeholder="请先选择学院再选择专业" filterable
                    clearable>
                    <el-option v-for="(v, i) in majorList" :key="i" :label="v.majorName" :value="v.majorId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="班级" prop="classId">
                <el-select v-model="params.classId" placeholder="请先选择专业再选择班级" filterable clearable>
                    <el-option v-for="(v, i) in classList" :key="i" :label="v.className" :value="v.classId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="年级" prop="gradeId">
                <el-select v-model="params.gradeId" placeholder="请选择年级" filterable clearable>
                    <el-option v-for="(v, i) in gradeList" :key="i" :label="v.gradeName" :value="v.gradeId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="学生姓名" prop="stuName">
                <el-input v-model="params.stuName" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="学号" prop="stuNo">
                <el-input v-model="params.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-form :model="exportForm" ref="exportForm" size="mini" :inline="true" label-width="120px">
            <el-form-item label="学年" prop="stuYearId">
                <el-select v-model="exportForm.stuYearId" placeholder="选择需要导出的学年">
                    <el-option v-for="(v, i) in year_list" :key="i" :label="v.stuYearName" :value="v.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="success" icon="el-icon-download" size="mini" @click="doExport">导出费用记录</el-button>
            </el-form-item>

            <el-form-item>
                <el-button type="success" icon="el-icon-download" size="mini"
                    @click="exportFdy">导出辅导员学生宿舍情况统计表</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="success" icon="el-icon-download" size="mini"
                    @click="exportDept">导出宿舍床位数情况统计</el-button>
            </el-form-item>
        </el-form>



        <el-table v-loading="loading" :data="tableData">
            <el-table-column label="学号" align="center" prop="stuNo" />
            <el-table-column label="班级" align="center" prop="className" />
            <el-table-column label="姓名" align="center" prop="stuName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="lookLog(scope.row)">
                        <span>查看住宿记录</span>
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-view" @click="lookTask(scope.row)">
                        <span>查看学生调宿计划</span>
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="params.pageNum" :limit.sync="params.pageSize"
            @pagination="getList" />

        <el-dialog :visible.sync="logV" title="住宿记录" width="80%">
            <h2>当前宿舍:{{ now_dorm }}</h2>
            <el-table :data="log_list">
                <el-table-column label="学号" align="center" prop="stuNo" />
                <el-table-column label="姓名" align="center" prop="stuName" />
                <el-table-column label="宿舍" align="center" prop="roomId" width="200">
                    <template slot-scope="scope">
                        <span>{{ scope.row.campusName + " " + scope.row.parkName + " " + scope.row.buildingName + " " +
                            scope.row.floorName + "层" + scope.row.roomNo }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="开始日期" align="center" prop="startDate" />
                <el-table-column label="结束日期" align="center" prop="endDate" />
                <el-table-column label="折合月数" align="center" prop="inMonth" />
                <el-table-column label="收费标准/10个月" align="center" prop="mainMoney" />
                <el-table-column label="应收费用" align="center" prop="needMoney" />
                <el-table-column label="农行卡号" align="center" prop="bankCard" />
                <el-table-column label="区间" align="center" prop="rangeName" />
                <el-table-column label="费用状态" align="center" prop="applyStatus">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.dms_record_status" :value="scope.row.applyStatus" />
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <el-dialog :visible.sync="taskV" title="查看学生调宿计划" width="90%">
            <el-table :data="task_list">
                <el-table-column label="学号" align="center" prop="stuNo" width="100" />
                <el-table-column label="姓名" align="center" prop="stuName" />
                <el-table-column label="旧宿舍" align="center" prop="oldDorm" width="200" />
                <el-table-column label="新宿舍" align="center" prop="newDorm" width="200" />
                <el-table-column label="任务类型" align="center" prop="taskType">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.dms_change_status" :value="scope.row.taskType" />
                    </template>
                </el-table-column>
                <el-table-column label="任务预执行日期" align="center" prop="taskWant" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.taskWant, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="任务执行时间" align="center" prop="taskRun" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.taskRun) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="任务执行状态" align="center" prop="taskStatus">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.dms_task_status" :value="scope.row.taskStatus" />
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>


    </div>
</template>
<script>
import { listJwc, getStuLog, exportFdy, exportDept } from "@/api/dormitory/new/stuDom";

import { fullLoading, isEmpty } from "@/api/helpFunc";

import { listStuTask } from "@/api/dormitory/new/task";

import { exportJwc } from "@/api/dormitory/new/record";

import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog, file2Xce, workbook2blobStyle } from "@/api/helpFunc";


import { listAllYear } from "@/api/stuCQS/basedata/year";

import { getDeptName } from "@/api/system/dept";
import { listMajors } from "@/api/stuCQS/basedata/majors";
import { listGrade } from "@/api/stuCQS/basedata/grade";
import { listClass } from "@/api/stuCQS/basedata/class";


export default {
    name: "stuDom_jwc",
    dicts: ['dms_approval_status', 'dms_task_status', 'dms_change_status', 'dms_record_status'],
    data() {
        return {
            loading: false,
            params: {
                pageSize: 10,
                pageNum: 1,
                stuNo: null
            },
            tableData: [],
            total: 0,
            logV: false,
            log_list: [],
            now_dorm: "暂无",

            taskV: false,
            task_list: [],

            exportForm: {
                stuYearId: null,
            },
            year_list: [],

            deptList: [],//学院列表
            majorList: [],//专业列表
            classList: [],//班级列表
            gradeList: [],//年级列表
        }
    },
    created() {
        this.listDept();
        this.listGrade();
        this.listAllYear();
        this.getList()
    },
    methods: {
        async listGrade() {
            let res = await listGrade();
            this.gradeList = [...res.rows];
        },

        async changeMajor() {
            if (!isEmpty(this.params.majorId)) {
                let sdata = {
                    pageNum: 1,
                    pageSize: 100,
                    majorId: this.params.majorId
                }
                let res = await listClass(sdata);
                this.classList = [...res.rows];
            } else {
                this.params.classId = null;
                this.classList = [];
            }

        },
        async changeDept() {
            if (!isEmpty(this.params.deptId)) {
                let sdata = {
                    collegeId: this.params.deptId,
                    pageNum: 1,
                    pageSize: 100
                }
                let res = await listMajors(sdata);
                this.majorList = [...res.rows];
            } else {
                this.params.majorId = null;
                this.majorList = [];
            }
        },
        async listDept() {
            let res = await getDeptName();
            this.deptList = [...res.data];
        },


        async exportDept() {
            let loading = fullLoading(this);
            let res = await exportDept();
            if (res.code == 200) {
                let data = [...res.data];
                data.map(x => {
                    delete (x.classId);
                    delete (x.teacherId);
                });

                const header = ['campusName', 'deptName', 'gradeName', 'all', 'allIn'];
                const header_zh = {
                    "campusName": "校区",
                    "gradeName": "年级",
                    "all": "总人数",
                    "allIn": "住宿人数",
                    'deptName': "学院"
                };

                const arrayWithHeader = [header_zh, ...data];

                var sheet1 = XLSX.utils.json_to_sheet(arrayWithHeader,
                    {
                        header: header,
                        skipHeader: true
                    });
                sheet1["!cols"] = [
                    { wch: 20 },
                    { wch: 40 },
                    { wch: 20 },
                    { wch: 10 },
                    { wch: 10 }
                ];


                // 创建一个新的空的workbook
                var wb = XLSX.utils.book_new();

                // 为每一个工作簿设置名称并添加到workbook（excel表）中
                XLSX.utils.book_append_sheet(wb, sheet1, "宿舍床位数情况统计");
                const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
                // 下载文档并添加文件名称
                openDownloadDialog(workbookBlob, "宿舍床位数情况统计.xlsx");  // 辅助函数openDownloadDialog

                loading.close();
            } else {
                loading.close();
            }
        },
        async exportFdy() {
            let loading = fullLoading(this);
            let res = await exportFdy();
            if (res.code == 200) {
                let data = [...res.data];
                data.map(x => {
                    delete (x.classId);
                    delete (x.teacherId);
                });

                const header = ['teacherName', 'className', 'all', 'boy', 'girl', 'allIn', 'boyIn', 'girlIn', 'deptName'];
                const header_zh = {
                    "teacherName": "辅导员",
                    "className": "班级",
                    "all": "总人数",
                    "boy": "男生",
                    "girl": "女生",
                    "allIn": "住宿人数",
                    "boyIn": "男生住宿人数",
                    "girlIn": "女生住宿人数",
                    'deptName': "学院"
                };

                const arrayWithHeader = [header_zh, ...data];

                var sheet1 = XLSX.utils.json_to_sheet(arrayWithHeader,
                    {
                        header: header,
                        skipHeader: true
                    });
                sheet1["!cols"] = [
                    { wch: 20 },
                    { wch: 40 },
                    { wch: 10 },
                    { wch: 10 },
                    { wch: 10 },
                    { wch: 10 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 40 },
                    { wch: 40 }
                ];

                sheet1['!merges'] = [];

                let tempFdy = null;
                let tempStart = 1;
                let tempEnd = 1;


                for (let i = 1; i < data.length; i++) {
                    if (i == 1) {
                        tempFdy = data[i].teacherName;
                    }

                    if (data[i].teacherName != tempFdy && i != 1) {
                        tempFdy = data[i].teacherName;
                        tempEnd = i;

                        let row = { s: { r: tempStart, c: 0 }, e: { r: tempEnd, c: 0 } };
                        sheet1['!merges'].push(row);

                        tempStart = i + 1;
                    }
                }



                // 创建一个新的空的workbook
                var wb = XLSX.utils.book_new();


                let range = XLSX.utils.decode_range(sheet1['!ref']);

                let headerStyle = {
                    border: {
                        top: {
                            style: 'thin',
                            color: {
                                auto: 1
                            }
                        },
                        left: {
                            style: 'thin',
                            color: {
                                auto: 1
                            }
                        },
                        right: {
                            style: 'thin',
                            color: {
                                auto: 1
                            }
                        },
                        bottom: {
                            style: 'thin',
                            color: {
                                auto: 1
                            }
                        }
                    },
                    alignment: { horizontal: 'center', vertical: 'center' }
                };

                for (let i = 1; i < data.length + 1; i++) {
                    for (var col = range.s.c; col <= range.e.c; col++) {
                        var cell = sheet1[XLSX.utils.encode_cell({ r: i, c: col })];
                        cell.s = headerStyle;
                        cell.v = cell.v;
                        cell.t = 's'; // 强制将单元格类型设置为字符串
                    }
                }


                // 为每一个工作簿设置名称并添加到workbook（excel表）中
                XLSX.utils.book_append_sheet(wb, sheet1, "辅导员学生宿舍情况统计表");
                const workbookBlob = workbook2blobStyle(wb);  // 辅助函数workbook2blob
                // 下载文档并添加文件名称
                openDownloadDialog(workbookBlob, "辅导员学生宿舍情况统计表.xlsx");  // 辅助函数openDownloadDialog

                loading.close();
            } else {
                loading.close();
            }
        },

        async listAllYear() {
            let res = await listAllYear();
            if (res.code == 200) {
                this.year_list = [...res.data];
            }
        },

        async lookTask(row) {
            let stuNo = row.stuNo;
            let loading = fullLoading(this);
            let res = await listStuTask(stuNo);
            loading.close();
            if (res.code == 200) {
                this.task_list = [...res.data];
                this.taskV = true;
            }
        },
        getApplyStatus(status) {
            switch (status) {
                case '6':
                    return '待确认';
                case '1':
                    return '学生已确认';
                case '2':
                    return '辅导员已确认';
                case '3':
                    return '学工已确认';
                default:
                    return '无状态';
            }
        },

        async doExport() {
            if (isEmpty(this.exportForm.stuYearId)) {
                this.$message.info("请先选择学年再导出");
                return;
            }
            let loading = fullLoading(this);
            let res = await exportJwc(this.exportForm);
            if (res.code == 200) {
                let data = [...res.data];
                let exportData = [];
                data.map(x => {
                    let temp = {};
                    temp['班级'] = x.className;
                    temp['学号'] = x.stuNo;
                    temp['姓名'] = x.stuName;

                    temp['辅导员'] = x.teacherName;
                    temp['辅导员电话'] = x.teacherPhone;
                    temp['总计费用'] = 0;
                    if (!isEmpty(x.recordTotalLog)) {
                        let log = x.recordTotalLog.split('|');
                        for (let i = 0; i < log.length; i++) {
                            if (!isEmpty(log[i])) {
                                let tempLog = log[i].split(',');

                                temp['宿舍号' + (i + 1)] = tempLog[0];
                                temp['住宿时间' + (i + 1)] = tempLog[1];
                                temp['折合月数' + (i + 1)] = tempLog[2];
                                temp['收费标准/10个月 金额（元）' + (i + 1)] = tempLog[3];
                                temp['应收费用' + (i + 1)] = tempLog[4];
                                temp['银行卡'] = tempLog[6];
                                temp['确认状态' + (i + 1)] = this.getApplyStatus(tempLog[8]);
                                temp['总计费用'] += parseFloat(tempLog[4]);
                            }
                        }
                    }

                    exportData.push(temp);
                });


                var sheet1 = XLSX.utils.json_to_sheet(exportData);

                sheet1["!cols"] = [
                    { wch: 40 },
                    { wch: 15 },
                    { wch: 10 },
                    { wch: 10 },
                    { wch: 18 },
                    { wch: 10 },

                    { wch: 30 },
                    { wch: 25 },
                    { wch: 10 },
                    { wch: 28 },
                    { wch: 10 },
                    { wch: 10 },

                    { wch: 30 },

                    { wch: 30 },
                    { wch: 25 },
                    { wch: 10 },
                    { wch: 28 },
                    { wch: 10 },
                    { wch: 10 },

                    { wch: 30 },
                    { wch: 25 },
                    { wch: 10 },
                    { wch: 28 },
                    { wch: 10 },
                    { wch: 10 },

                    { wch: 30 },
                    { wch: 25 },
                    { wch: 10 },
                    { wch: 28 },
                    { wch: 10 },
                    { wch: 10 },

                    { wch: 30 },
                    { wch: 25 },
                    { wch: 10 },
                    { wch: 28 },
                    { wch: 10 },
                    { wch: 10 },

                ];

                // 创建一个新的空的workbook
                var wb = XLSX.utils.book_new();
                // 为每一个工作簿设置名称并添加到workbook（excel表）中
                XLSX.utils.book_append_sheet(wb, sheet1, "费用记录");
                const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
                // 下载文档并添加文件名称
                openDownloadDialog(workbookBlob, "费用记录.xlsx");  // 辅助函数openDownloadDialog

                loading.close();
            } else {
                loading.close();
            }

        },

        async lookLog(row) {
            this.now_dorm = "暂无";
            let stuNo = row.stuNo;
            let loading = fullLoading(this);
            let res = await getStuLog(stuNo);
            loading.close();
            if (res.code == 200) {
                console.log(res);
                let data = { ...res.data };
                let temp = [...data.record];

                let i = 0;
                temp.map(x => {
                    if (x.startDate == "1970-01-01") {
                        x.startDate = "学期开始";
                    }
                    if (x.endDate == "1970-01-01") {
                        x.endDate = "学期结束";
                    }
                    i++;
                });
                this.log_list = [...temp];
                if (data.dormStu != null) {
                    let temp = { ...data.dormStu };
                    this.now_dorm = temp.campusName + " " + temp.parkName + " " + temp.buildingName + " " + temp.floorName + "层" + temp.roomNo;
                }
                this.logV = true;
            }
        },
        async getList() {
            this.loading = true;
            let res = await listJwc(this.params);
            this.loading = false;
            if (res.code == 200) {
                this.total = res.total;
                this.tableData = [...res.rows];
            }
        },
        handleQuery() {
            this.params.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
    }
}


</script>